package com.dmai.capacity.platform.config;

import com.dmai.capacity.platform.common.dto.ResponseEntity;
import com.dmai.capacity.platform.common.exception.BusinessException;
import com.dmai.capacity.platform.constants.ExceptionEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * RestControllerAdvice，统一异常处理
 */
@Slf4j
@RestControllerAdvice
public class ExceptionHandlerConfig {

    /**
     * 业务异常处理
     *
     * @param e 业务异常
     * @return
     */
    @ExceptionHandler(value = BusinessException.class)
    @ResponseBody
    public ResponseEntity exceptionHandler(BusinessException e) {
        log.error(e.toString());
        return ResponseEntity.of(e.getCode(), e.getErrorMsg());
    }

    /**
     * 参数移除
     *
     * @param e 业务异常
     * @return
     */
    @ExceptionHandler(value = IllegalArgumentException.class)
    @ResponseBody
    public ResponseEntity exceptionHandler(IllegalArgumentException e) {
        log.error(e.toString());
        return ResponseEntity.of(ExceptionEnum.COMMON.getCode(), e.getMessage());
    }


    /**
     * 未知异常处理
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseEntity exceptionHandler(Exception e) {
        // 把错误信息输入到日志中
        log.error(String.valueOf(e));
        return ResponseEntity.of(ExceptionEnum.COMMON.getCode(), ExceptionEnum.COMMON.getMsg());
    }

    /**
     * 参数校验异常
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity handlerMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();

        // 所有参数异常信息
        List<ObjectError> allErrors = bindingResult.getAllErrors();

        return ResponseEntity.failed(allErrors.get(0).getDefaultMessage());
    }

    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(BindException.class)
    public ResponseEntity handlerBindException(BindException e) {
        BindingResult bindingResult = e.getBindingResult();

        // 所有参数异常信息
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        return ResponseEntity.failed(allErrors.get(0).getDefaultMessage());
    }

}